package Core;

import Logic.Business;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import microgame.toolset.database.DatabaseControl;
import microgame.toolset.serverconfig.ServerConfig;

public final class WebSocketServer {

    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void main(String[] args) throws Exception {

        ////////////////////////////////////////////////////////////
        //Database Init
        DatabaseControl.Instance().Init();
        ServerConfig.Instance().Init();

        ////////////////////////////////////////////////////////////
        //Game Thread
        Business business = new Business();
        business.start();

        ////////////////////////////////////////////////////////////
        //Netty

        //server config
        String startDir = System.getProperty("user.dir");
        ConfigManager.Instance().loadConfig(startDir + "/Config/server.cfg");

        //
        LogicFramework.Instance().init();

        //Netty start
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new ClientInsideServer())
                    .childHandler(new WebSocketServerInitializer());

            String host = ConfigManager.Instance().getHost();
            int port = ConfigManager.Instance().getPort();

            Channel ch = b.bind(port).sync().channel();

            Log4j2.LOGGER.warn("Operating system is: " +  OS);
            Log4j2.LOGGER.debug("Detect the problem.");
            Log4j2.LOGGER.info("Open your web browser and navigate to " + "http://" + host + ":" + port + '/');
            Log4j2.LOGGER.info("Or you can connect to websocket directly thru: ws://" + host + ":" + port + "/websocket");

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
